package com.wjb.xietong.ota.tab1;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.wjb.xietong.R;
import com.wjb.xietong.control.AsyncImageLoader;
import com.wjb.xietong.control.WJBControl;
import com.wjb.xietong.datamanager.LoginUserDataManager;
import com.wjb.xietong.datamanager.WJBDataManager;
import com.wjb.xietong.ota.BaseFM;
import com.wjb.xietong.ota.OTAMainMenu;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.topic.ReplyParam;
import com.wjb.xietong.server.topic.TopicParam;
import com.wjb.xietong.server.topic.TopicResponse;
import com.wjb.xietong.server.topic.TopicResponse.TopicAttachmentInfo;
import com.wjb.xietong.server.topic.TopicResponse.TopicInfo;
import com.wjb.xietong.util.TopicTrigger;
import com.wjb.xietong.util.TopicTriggerListener;
import com.wjb.xietong.util.EnumDefine.Login_User_Info;
import com.wjb.xietong.util.TopicTrigger_MGR;
import com.wjb.xietong.view.CVCirclePictureView;
import com.wjb.xietong.view.PullToRefreshView;
import com.wjb.xietong.view.PullToRefreshView.OnFooterRefreshListener;
import com.wjb.xietong.view.PullToRefreshView.OnHeaderRefreshListener;

public class FMTab1 extends BaseFM  implements OnHeaderRefreshListener, OnFooterRefreshListener, TopicTriggerListener{
	private final int MESSAGE_FINISH_GET_DATA = 1;
	
	private TextView txtNotice;
	private ListView mListView;
	private ListAdapter mAdapter;
	
	private PullToRefreshView mPullToRefreshView;
	private final int PAGE_INDEX = 1;
	private final int NUM_EVERY_PAGE = 10;
	private int mPageIndex = 1;
	
	private List<TopicInfo> topicList = new ArrayList<TopicInfo>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		TopicTrigger_MGR.Instance().registerTopicObserver(this);
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mPageIndex = 1;
		View view = super.onCreateView(inflater, container, savedInstanceState);
		setContentField(inflater.inflate(R.layout.fm_tab1, null));
		setTopBarAndAction(getString(R.string.STR_TAB_01), null, new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
			}
		}, R.drawable.ico_add_status);
		return view;
	}
	
	@Override
	protected void findView(View v) {
		mPullToRefreshView = (PullToRefreshView) v.findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this, PAGE_INDEX);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		
		txtNotice = (TextView)v.findViewById(R.id.id_work_circle_notice);
		
		mListView = (ListView)v.findViewById(R.id.id_listview);
		mAdapter = new ListAdapter(getActivity());
		mListView.setAdapter(mAdapter);
		mListView.setItemsCanFocus(false);
		
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getActivity(), OTAWorkMessageDetail.class);
				intent.putExtra("topic_id", topicList.get(arg2).getTopicId());
				intent.putExtra("topic_praiseFlag", topicList.get(arg2).getZanFlag());
				startActivity(intent);
			}
		});
		
		requestData(true, mPageIndex, NUM_EVERY_PAGE);
	}
	
	@Override
	protected void setOnClickEvent() {
		// TODO Auto-generated method stub
		super.setOnClickEvent();
	}
	
	Handler handler = new Handler(Looper.getMainLooper()){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_FINISH_GET_DATA:
					mAdapter.notifyDataSetChanged();
					break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	public void onDestroy() {
		TopicTrigger_MGR.Instance().removeTopicObserver(this);
		super.onDestroy();
	};
	
	private void requestData(final boolean isRefresh, final int pageIndex, final int endRow){
		long uniqueID = Calendar.getInstance().getTimeInMillis();
		IRequestResultListener listener = new IRequestResultListener() {

			@Override
			public void requestSuccess(long requestUniqueID) {
				if(isRefresh){
					topicList.clear();
				}
				setTopicListData();
			}

			@Override
			public void requestFaield(long requestUniqueID,
					String errCode, String errMsg) {
				System.out.println("cdy test: failed");
			}
		};
		TopicParam param8 =  new TopicParam();
		param8.setCompanyId((Long)LoginUserDataManager.getLoginUserInfo(Login_User_Info.COM_ID));
		param8.setPageNo(pageIndex);
		param8.setPageSize(endRow);
		param8.setUserId((Long)LoginUserDataManager.getLoginUserInfo(Login_User_Info.ID));
		WJBControl.requestGetTopicList(uniqueID, param8, listener);
	}
	
	private void setTopicListData(){
		TopicResponse response = WJBDataManager.getTopicResponseInfo();
		if(null != response.getTopicInfoList()){
			topicList.addAll(response.getTopicInfoList());
		}
		handler.sendEmptyMessage(MESSAGE_FINISH_GET_DATA);
	}

	public class ListAdapter extends BaseAdapter{
		private LayoutInflater mInflater; 
        
        public ListAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }
        
		@Override
		public int getCount() {
			if(topicList == null){
				return 0;
			}else{
				return topicList.size();
			}
		}

		@Override
		public Object getItem(int arg0) {
			if(topicList == null){
				return null;
			}else{
				return topicList.get(arg0);
			}
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_work_circle_list,
						null);
				holder = new ViewHolder();
				/* 得到各个控件的对象 */
				holder.icon = (CVCirclePictureView) convertView.findViewById(R.id.head_view);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.llDetail = (LinearLayout) convertView.findViewById(R.id.id_item_txt_img_vector);
				holder.praise = (Button) convertView.findViewById(R.id.btn_praise);
				holder.comment = (Button) convertView.findViewById(R.id.btn_comment);

				convertView.setTag(holder); // 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag(); // 取出ViewHolder对象
			}

			if(topicList != null){
				final TopicInfo info = topicList.get(position);
				AsyncImageLoader.Instance().loadDrawableForImageView(info.getIconUrl(), holder.icon, R.drawable.taskdetail_temp_flag);
				holder.name.setText(info.getNick());
				holder.date.setText(info.getReplyDate());
				
				//详细内容区域，包含文字跟图片
				holder.llDetail.removeAllViews();
				String contentInfo = info.getContent();
				if(null != contentInfo){
					TextView txt = new TextView(getActivity());
					txt.setText("" + contentInfo);
					holder.llDetail.addView(txt, new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.MATCH_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT));
				}
				List<TopicAttachmentInfo> attachInfoList = info.getAttachmentInfoList();
				for (TopicAttachmentInfo attachInfo : attachInfoList) {
					if (null != attachInfo.getImages()) {// 图片
						ImageView img = new ImageView(getActivity());
						img.setClickable(true);
						img.setScaleType(ScaleType.FIT_START);
						AsyncImageLoader.Instance().loadDrawableForImageView(
										attachInfo.getImages(), img,
										R.drawable.trans);
						holder.llDetail.addView(img, new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.MATCH_PARENT,
								LinearLayout.LayoutParams.WRAP_CONTENT));
					}else if(null != attachInfo.getFilename()){
						//TODO
//						Button img = new ImageView(getActivity());
//						img.setClickable(true);
//						img.setScaleType(ScaleType.FIT_START);
//						AsyncImageLoader.Instance().loadDrawableForImageView(
//										attachInfo.getImages(), img,
//										R.drawable.refersh);
//						holder.llDetail.addView(img, new LinearLayout.LayoutParams(
//								LinearLayout.LayoutParams.MATCH_PARENT,
//								LinearLayout.LayoutParams.WRAP_CONTENT));
					}
				}
				
				if(info.getZanFlag() == 1){//已赞
					holder.praise.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ico_praise_b), null, null, null);
					holder.praise.setTextColor(getResources().getColor(R.color.wc_has_praise));
					holder.praise.setBackgroundResource(R.drawable.circle_btn_bg_b);
				}else{//未赞
					holder.praise.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ico_praise_a), null, null, null);
					holder.praise.setTextColor(getResources().getColor(R.color.wc_no_praise));
					holder.praise.setBackgroundResource(R.drawable.circle_btn_bg_a);
				}
				if(info.getLike() == 0){
					holder.praise.setText(getString(R.string.STR_WORK_CIRCLE_02));
				}else if(info.getLike() > 99){
					holder.praise.setText("99+");
				}else{
					holder.praise.setText(info.getLike() + "");
				}
				holder.praise.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(info.getZanFlag() == 1){//已赞
							requestPraiseById(position, info, 0);
						}else{
							requestPraiseById(position, info, 1);
						}
					}
				});
				if(info.getReplyCount() == 0){
					holder.comment.setText(getString(R.string.STR_WORK_CIRCLE_03));
				}else if(info.getReplyCount() > 99){
					holder.comment.setText("99+");
				}else{
					holder.comment.setText(info.getReplyCount() + "");
				}
				holder.comment.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(), OTAComment.class);
						intent.putExtra("action_comment", info.getTopicId());
						startActivity(intent);
					}
				});
			}
			
			return convertView;
		}
		
		/*存放控件 的ViewHolder*/
		public final class ViewHolder {
			public CVCirclePictureView icon;
			public TextView name;
			public TextView date;
			public LinearLayout llDetail;
			public Button praise;
			public Button comment;
		}
	}
	
	private void requestPraiseById(final int position, TopicInfo info, final int praiseFlag){
		long uniqueID = Calendar.getInstance().getTimeInMillis();
		IRequestResultListener listener = new IRequestResultListener() {

			@Override
			public void requestSuccess(long requestUniqueID) {
				System.out.println("cdy test: success");
				topicList.get(position).setZanFlag(praiseFlag);
				if(praiseFlag == 1){
					topicList.get(position).setLike(topicList.get(position).getLike() + 1);
				}else{
					topicList.get(position).setLike(topicList.get(position).getLike() - 1);
				}
				handler.sendEmptyMessage(MESSAGE_FINISH_GET_DATA);
			}

			@Override
			public void requestFaield(long requestUniqueID,
					String errCode, String errMsg) {
				System.out.println("cdy test: failed");
			}
		};
		//获取已赞联系人列表
		ReplyParam param4 = new ReplyParam();
		param4.setCompanyId((Long) LoginUserDataManager.getLoginUserInfo(Login_User_Info.COM_ID));
		param4.setZanType(praiseFlag);//(0:取消赞 1:点赞)
		param4.setTopicId(info.getTopicId());
		param4.setUserId((Long) LoginUserDataManager.getLoginUserInfo(Login_User_Info.ID));
		WJBControl.requestReply(uniqueID, param4, listener);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPullToRefreshView.onFooterRefreshComplete();
				mPageIndex = pageIndex;
				requestData(false, pageIndex, NUM_EVERY_PAGE);
				if(txtNotice != null){
					txtNotice.setVisibility(View.GONE);
				}
			}
		}, 1000);
			
	}
	
	@Override
	public void onHeaderRefresh(PullToRefreshView view, final int pageIndex) {
		// TODO Auto-generated method stub
		mPullToRefreshView.postDelayed(new Runnable() {
	
			@Override
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete();
				mPageIndex = 0;
				requestData(true, pageIndex, NUM_EVERY_PAGE);
				if(txtNotice != null){
					txtNotice.setVisibility(View.GONE);
				}
			}
		}, 1000);
	}
	
	@Override
	public void onTopicTrigger(TopicTrigger trigger) {
		// TODO Auto-generated method stub
		Activity activity = app_.getActManager().currentActivity();
		if(activity instanceof OTAMainMenu){
			OTAMainMenu actMain = (OTAMainMenu)activity;
			actMain.noticeRedPot();
			if(txtNotice != null){
				txtNotice.setVisibility(View.VISIBLE);
				txtNotice.setText(String.format(getString(R.string.STR_WORK_CIRCLE_01), trigger.getlParam1() + ""));
			}
		}
	}
}